from django.shortcuts import render
from django.http import JsonResponse
import json
from django.views import View


# Retrieve a single task
def index(request):
    # task = get_object_or_404(Task, pk=pk)
    return render(request, "index.html")


from .websocket import check_connection


class LoginView(View):
    def post(self, request):
        try:
            # 获取数据
            data = json.loads(request.body.decode("utf-8"))
            # 验证数据
            nickname = data.get('nickname')
            if not nickname:
                print(' 缺少用户名', )
                raise Exception('缺少用户名')

            # 判断该昵称是否被使用
            nickname = data['nickname']
            if check_connection(nickname):
                raise Exception('该昵称已被使用，无法建立连接')

            # 假设auth等于 nikename TODO: 只有要改成token
            user_id = nickname

            res = {
                'code': '200',
                'data': {
                    'user_id': user_id,
                }
            }

            print('[res]', res)
            return JsonResponse(res)
        except Exception as e:
            return JsonResponse({
                'code': '201',
                'msg': str(e)
            })

        pass
